//
//  CustomFileManager.swift
//  MeasureMould
//
//  Created by iOS on 2021/7/2.
//

import Foundation



class CustomFileManager:NSObject {

    var documentController = UIDocumentInteractionController()
    var locFileName:String = ""
    var backView:UIView = UIView()
    override init() {
        super.init()
        creatCSV()
    }

    func creatCSV(){
        let docPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as String
        let time = Date()
        let timeFormatter = DateFormatter()
        timeFormatter.dateFormat = "yyyyMMdd'at'HH:mm:ss.SSS"
        let timeStr = timeFormatter.string(from: time) as String
        let fileName = timeStr + ".csv"
        let filePath = docPath.appending("/" + fileName)
        print("filePath === ", filePath)
        self.locFileName = filePath
        self.creatFile(fileName: filePath)
        self.writeCSV(fileName: filePath)

        self.readFileCSV(fileName: filePath)
    }

    func creatFile(fileName:String){
        let fileManager = FileManager.default
        try? fileManager.removeItem(atPath: fileName)
        if !(fileManager.createFile(atPath: fileName, contents: nil, attributes: nil)) {
            print("不能创建文件")
        }
    }

    func writeCSV(fileName:String){
        let fileHandle = FileHandle(forUpdatingAtPath: fileName)
        //将节点调到文件末尾
        fileHandle?.seekToEndOfFile()
        let header = "面积(m²), 周长(m), 经度, 纬度 \r\n"
        let strData = header.data(using: .utf8)
        fileHandle?.write(strData!)
        let locatManager = LocatFileManager()
        for item in locatManager.coordList {
            let str = String(locatManager.mathArea) + "," + String(locatManager.mathPermater) + "," + String(item.latitude) + "," + String(item.longitude) + "\r\n"
            let latLngData  = str.data(using: .utf8)
            fileHandle?.write(latLngData!)
        }
        fileHandle?.closeFile()
    }


    func readFileCSV(fileName:String){
        do {
//            let cfEncoding = CFStringEncodings.GB_2312_80
//            let endcoding = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEncoding.rawValue))
//            let fileGBKContents = try String(contentsOfFile: path!, encoding: String.Encoding(rawValue: endcoding))
//            let List = fileGBKContents.components(separatedBy: "\r\n")

            let fileContents = try String(contentsOfFile: fileName, encoding: .utf8)
            let List = fileContents.components(separatedBy: "\r\n")
            let subList = List[3 ..< List.count-1]
            debugPrint(subList)

        } catch let error {
            print("GBK格式解析错误", error.localizedDescription)
        }
    }

    func openDocumentInResureceFloder(view:UIView){
        self.backView = view
        let url = URL(fileURLWithPath: self.locFileName)
        self.documentController = UIDocumentInteractionController(url: url)
        self.documentController.delegate = self
//        documentController.uti = "com.microsoft.excel.xls"
        self.documentController.presentOpenInMenu(from: CGRect.zero, in: self.backView, animated: true)
    }

}

extension CustomFileManager: UIDocumentInteractionControllerDelegate {
    func documentInteractionControllerViewForPreview(_ controller: UIDocumentInteractionController) -> UIView? {
        return self.backView
    }
}
